<?php

/**
 * This file is part of easyCMS.
 *
 * (c) 2023 easyCMS <easyCMS@easycms.net.cn>
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace app\admin\controller;

use app\admin\model\BaseModel;
use app\admin\model\SystemAdmin;
use app\admin\model\SystemMenu;
use app\admin\validate\MenuValidate;
use Exception;
use support\Db;
use support\Request;

class MenuController
{
    #[permits('admin:menu:list')]
    public function index(Request $request): \support\Response
    {
        return view('menu/menuList');
    }

    /**
     * 菜单列表
     */
    #[permits('admin:menu:list')]
    public function menuListData(Request $request): \support\Response
    {
        $admin = admin();
        $menu  = null;
        if ($admin['user_type'] === SystemAdmin::SUPER_ADMIN) {
            $menu = SystemMenu::where('status', 1)->orderBy('sort', 'ASC')->get()->toArray();
        }

        return json(['code' => 0, 'msg' => '', 'count' => 0, 'data' => $menu]);
    }

    /**
     * 数组转换为treeTable结构
     */
    private function getTree(mixed $data, mixed $pid): array
    {
        $list = [];

        foreach ($data as $k => $v) {
            if ((int) ($v['pid']) === $pid) {
                $ss['title']    = $v['title']; // 这里可以加个层级次数
                $ss['value']    = $v['id'];
                $ss['level']    = $v['level'];
                $ss['children'] = self::getTree($data, (int) ($v['id']));
                if ($ss['children'] === null) {
                    unset($ss['children']);
                }
                $list[] = $ss;
            }
        }

        return $list;
    }

    /**
     * 新增菜单
     */
    #[permits('admin:menu:add')]
    public function menuAdd(): \support\Response
    {
        $data['menu'] = new SystemMenu();
        $menuAll      = SystemMenu::where('type', SystemMenu::TYPE_MENU)->where('status', BaseModel::STATUS_NORMAL)->orderBy('sort', 'ASC')->get()->toArray();
        array_unshift($menuAll, ['id' => 0, 'title' => '根菜单', 'pid' => -1, 'level' => 0]);
        $data['menuAll'] = $this->getTree($menuAll, -1);

        return view('menu/menuEdit', $data);
    }

    /**
     * 新增菜单
     */
    #[permits('admin:menu:add')]
    public function doMenuAdd(Request $request): \support\Response
    {
        $code = 0;
        $msg  = '';

        $id      = $request->post('id');
        $pid     = $request->post('pid');
        $level   = $request->post('level');
        $title   = $request->post('title');
        $type    = $request->post('type');
        $href    = $request->post('href');
        $permits = $request->post('permits');
        $target  = $request->post('target');
        $icon    = $request->post('icon');
        $sort    = $request->post('sort');

        $validate = new MenuValidate();
        if ($validate->check($request->post())) {
            $menu          = new SystemMenu();
            $menu->level   = $level + 1;
            $menu->status  = BaseModel::STATUS_NORMAL;
            $menu->pid     = $pid;
            $menu->title   = $title;
            $menu->type    = $type;
            $menu->href    = $href;
            $menu->permits = $permits;
            $menu->target  = $target;
            $menu->icon    = $icon;
            $menu->sort    = $sort;
            Db::beginTransaction();

            try {
                $menu->save();
                // 判断是否自动增加CRUD权限
                if ((int) ($menu->level) === 3 && (int) ($menu->type) === SystemMenu::TYPE_MENU) {
                    $insertBatchData   = [];
                    $insertBatchData[] = [
                        'pid'     => $menu->id,
                        'title'   => '新增',
                        'type'    => SystemMenu::TYPE_BUTTON,
                        'permits' => $menu->permits . ':add',
                        'level'   => $menu->level + 1,
                    ];
                    $insertBatchData[] = [
                        'pid'     => $menu->id,
                        'title'   => '列表',
                        'type'    => SystemMenu::TYPE_BUTTON,
                        'permits' => $menu->permits . ':list',
                        'level'   => $menu->level + 1,
                    ];
                    $insertBatchData[] = [
                        'pid'     => $menu->id,
                        'title'   => '修改',
                        'type'    => SystemMenu::TYPE_BUTTON,
                        'permits' => $menu->permits . ':edit',
                        'level'   => $menu->level + 1,
                    ];
                    $insertBatchData[] = [
                        'pid'     => $menu->id,
                        'title'   => '删除',
                        'type'    => SystemMenu::TYPE_BUTTON,
                        'permits' => $menu->permits . ':delete',
                        'level'   => $menu->level + 1,
                    ];
                    print_r($insertBatchData);
                    SystemMenu::insert($insertBatchData);
                }
                Db::commit();
                $msg = '操作成功';
            } catch (Exception $e) {
                Db::rollBack();
                $code = 1;
                $msg  = '操作失败';
            }
        } else {
            $code = 1;
            $msg  = $validate->getError();
        }

        return json(['code' => $code, 'msg' => $msg]);
    }

    /**
     * 编辑菜单
     */
    #[permits('admin:menu:edit')]
    public function menuEdit(Request $request): \support\Response
    {
        $msg          = '';
        $id           = $request->get('id');
        $menu         = SystemMenu::find($id);
        $data['menu'] = $menu;
        $menuAll      = SystemMenu::where('type', SystemMenu::TYPE_MENU)->where('status', BaseModel::STATUS_NORMAL)->orderBy('sort', 'ASC')->get()->toArray();
        array_unshift($menuAll, ['id' => 0, 'title' => '根菜单', 'pid' => -1, 'level' => 0]);
        $data['menuAll'] = $this->getTree($menuAll, -1);

        return view('menu/menuEdit', $data);
    }

    /**
     * 编辑菜单
     */
    #[permits('admin:menu:edit')]
    public function doMenuEdit(Request $request): \support\Response
    {
        $code = 0;
        $msg  = '';

        $id      = $request->post('id');
        $pid     = $request->post('pid');
        $level   = $request->post('level');
        $title   = $request->post('title');
        $type    = $request->post('type');
        $href    = $request->post('href');
        $permits = $request->post('permits');
        $target  = $request->post('target');
        $icon    = $request->post('icon');
        $sort    = $request->post('sort');

        $validate = new MenuValidate();
        if ($validate->check($request->post())) {
            $menu          = SystemMenu::find($id);
            $menu->level   = $level;
            $menu->pid     = $pid;
            $menu->title   = $title;
            $menu->type    = $type;
            $menu->href    = $href;
            $menu->permits = $permits;
            $menu->target  = $target;
            $menu->icon    = $icon;
            $menu->sort    = $sort;
            if ($menu->save()) {
                $msg = '操作成功';
            } else {
                $code = 1;
                $msg  = '操作失败';
            }
        } else {
            $code = 1;
            $msg  = $validate->getError();
        }

        return json(['code' => $code, 'msg' => $msg]);
    }

    /**
     * 删除菜单
     */
    #[permits('admin:menu:delete')]
    public function menuDelete(Request $request): \support\Response
    {
        $code  = 0;
        $msg   = '';
        $id    = $request->post('id');
        $count = SystemMenu::where('pid', $id)->where('status', BaseModel::STATUS_NORMAL)->count();
        if ($count > 0) {
            $msg = '请先删除子菜单';
        } else {
            $menu = SystemMenu::find($id);
            if ($menu !== '' && $menu->id > 0) {
                if ($menu->delete()) {
                    $msg = '删除成功';
                } else {
                    $msg = '删除失败';
                }
            }
        }

        return json(['code' => $code, 'msg' => $msg]);
    }
}
